<!-- src/components/main/top.vue -->
<template>
  <div class="model-container">
    <div class="control-panel">
      <button class="refresh-btn" @click="resetView">
        <img src="@/assets/svg/refresh.svg" class="fas fa-sync-alt" />
      </button>
    </div>

    <div class="body-box" ref="container">
      <div v-if="tooltip.visible" class="tooltip" :style="tooltipStyle">
        <div class="tooltip-header">{{ tooltip.name }}</div>
        <div class="tooltip-content">
          <div v-for="(value, key) in tooltip.params" :key="key" class="param-row">
            <span class="param-name">{{ key }}:</span>
            <span class="param-value">{{ value }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, reactive } from "vue";
import { SceneManager } from "@/utils/SceneManager.js";
import { ModelManager } from "@/utils/ModelManager.js";
import { InteractionController } from "@/utils/InteractionController.js";

// 定义容器引用
const container = ref(null);

// Three.js 相关变量
let sceneManager, modelManager, interactionController;
let animationFrameId;
let resizeObserver;
let mouseMoveHandler;

// 工具提示状态
const tooltip = reactive({
  visible: false,
  name: "",
  params: {},
  position: { x: 0, y: 0 },
});

// 计算工具提示样式
const tooltipStyle = ref({
  left: "0px",
  top: "0px",
  display: "none",
});

// 动画循环
const animate = () => {
  animationFrameId = requestAnimationFrame(animate);
  sceneManager?.render();
};

// 工具提示处理函数
const handleTooltip = (tooltipData) => {
  Object.assign(tooltip, tooltipData);

  if (tooltipData.visible && tooltipData.position) {
    tooltipStyle.value = {
      left: `${tooltipData.position.x + 15}px`, // 鼠标右侧15px
      top: `${tooltipData.position.y - 10}px`, // 鼠标上方10px
      display: "block",
    };
  } else {
    tooltipStyle.value.display = "none";
  }
};

// 切换内部结构显示/隐藏
const toggleInternalStructure = () => {
  if (modelManager) {
    modelManager.toggleInternalStructureView();
    isInternalStructureHidden.value = !isInternalStructureHidden.value;
  }
};

// 重置模型到初始状态（恢复所有部件可见性和颜色，但保持摄像头位置不变）
const resetView = () => {
  // 重置模型状态，但不改变摄像头位置
  if (modelManager) {
    // 恢复所有部件颜色到初始状态
    modelManager.restoreAllColors();

    // 显示所有部件（恢复可见性）
    modelManager.showAllInternalStructure();

    // 重新应用初始高亮（延迟执行确保状态正确恢复）
    setTimeout(() => {
      modelManager.highlightMultipleParts();
      // 重新隐藏油箱（根据原始加载逻辑）
    }, 50);
  }

  // 重置控制器状态（保持当前位置）
  if (sceneManager) {
    const controls = sceneManager.getControls();
    if (controls) {
      controls.reset();
    }
  }
};

// 初始化场景和模型
const initScene = () => {
  if (!container.value) {
    setTimeout(initScene, 100);
    return;
  }

  sceneManager = new SceneManager(container.value);

  if (sceneManager.init()) {
    modelManager = new ModelManager(sceneManager.getScene());

    modelManager.loadModel("/models/test4.glb").then((model) => {
      if (model) {
        interactionController = new InteractionController(
          sceneManager.getRenderer(),
          sceneManager.getCamera(),
          modelManager.getModel(),
          modelManager
        );

        interactionController.setTooltipCallback(handleTooltip);

        // 保存事件处理函数引用以便后续移除
        mouseMoveHandler = interactionController.onMouseMove;
        sceneManager
          .getRenderer()
          .domElement.addEventListener("mousemove", mouseMoveHandler);
      }
    });

    animate();
  } else {
    setTimeout(initScene, 100);
  }
};

// 处理窗口大小变化
const handleResize = () => {
  sceneManager?.resize();
};

// 生命周期钩子：组件挂载后初始化
onMounted(() => {
  nextTick(() => {
    resizeObserver = new ResizeObserver(() => {
      handleResize();
    });

    if (container.value) {
      resizeObserver.observe(container.value);
    }

    initScene();
  });
});

// 生命周期钩子：组件卸载前清理资源
onBeforeUnmount(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
  }

  // 移除鼠标事件监听器
  if (mouseMoveHandler && sceneManager?.getRenderer()) {
    sceneManager
      .getRenderer()
      .domElement.removeEventListener("mousemove", mouseMoveHandler);
  }

  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
  }

  interactionController?.dispose();
  modelManager?.dispose();
  sceneManager?.dispose();
});
</script>

<style lang="less" scoped>
/* 样式部分保持不变 */
.model-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.body-box {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  width: 100%;
  flex: 1;
  min-height: 0;
  position: relative;
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  overflow: hidden;

  &>canvas {
    width: 100% !important;
    height: 100% !important;
    display: block;
    background-color: transparent;
    cursor: pointer;
  }
}

/* 控制面板样式 - 右上角浮动 */
.control-panel {
  position: absolute;
  top: 30px;
  right: 30px;
  z-index: 100;
  display: flex;
  gap: 12px;
}

/* 优化的控制按钮样式 - 调整为更适合深蓝背景的颜色 */
.control-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #2980b9 0%, #2c3e50 100%);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  backdrop-filter: blur(10px);
  background-color: rgba(74, 144, 226, 0.9);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
    background-color: rgba(74, 144, 226, 1);
  }

  &:active {
    transform: translateY(0);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  &:focus {
    outline: none;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15),
      0 0 0 2px rgba(74, 144, 226, 0.3);
  }
}

.refresh-btn {
  background: rgba(79, 195, 247, 0.2);
  border: 1px solid rgba(79, 195, 247, 0.5);
  color: #4fc3f7;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: rgba(79, 195, 247, 0.4);
    transform: rotate(90deg);
  }
}

.tooltip {
  position: fixed;
  background: rgba(0, 0, 0, 0.85);
  color: white;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  z-index: 1000;
  min-width: 220px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  pointer-events: none;
  transition: opacity 0.2s ease;

  &::after {
    content: "";
    position: absolute;
    bottom: -10px;
    left: 20px;
    border-width: 10px 10px 0;
    border-style: solid;
    border-color: rgba(0, 0, 0, 0.85) transparent transparent;
  }

  .tooltip-header {
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 8px;
    color: #4fc3f7;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    padding-bottom: 6px;
  }

  .tooltip-content {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .param-row {
    display: flex;
    justify-content: space-between;
  }

  .param-name {
    opacity: 0.8;
  }

  .param-value {
    font-weight: 500;
    color: #2ecc71;
  }
}
</style>